<template>
  <div class="register_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form
            class="register_form"
            :model="registerForm"
            :rules="rules"
            ref="registerForms"
        >
          <el-row
          ><img
              src="../../assets/images/logo.png"
              style="width: 128px; height: 128px"
          />
            <h1 style="text-align: center; line-height: 128px">Hello</h1>
          </el-row>

          <h2>欢迎来到电商平台，请注册您的账号</h2>

          <el-form-item prop="userAccount">
            <el-input
                style="width: 400px"
                placeholder="请输入您的账号"
                :prefix-icon="User"
                v-model="registerForm.userAccount"
            ></el-input>
          </el-form-item>
          <el-form-item prop="userPassword">
            <el-input
                style="width: 400px"

                placeholder="请输入您的密码"
                type="password"
                :prefix-icon="Lock"
                v-model="registerForm.userPassword"
                show-password
            ></el-input>
          </el-form-item>
          <el-form-item prop="checkPassword">
            <el-input
                style="width: 400px"
                placeholder="请再次输入您的密码"
                type="password"
                :prefix-icon="Lock"
                v-model="registerForm.checkPassword"
                show-password
            ></el-input>
          </el-form-item>
          <el-form-item prop="role">
            <el-select
                style="width: 400px"
                v-model="registerForm.role"
                placeholder="请选择角色"
            >
              <el-option label="用户" value="user"></el-option>
              <el-option label="商家" value="merchant"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="email">
            <el-input
                style="width: 400px"
                placeholder="请输入您的邮箱"
                v-model="registerForm.email"
                :prefix-icon="Message"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
                style="width: 290px"
                placeholder="请输入验证码"
                v-model="registerForm.code"
            ></el-input>
            <el-button
                style="margin-left: 10px"
              :disabled="isSendingCode"
              @click="sendVerificationCode"
              type="primary"
              size="default"
          >{{ isSendingCode ? `${countdown}s后重新发送` : "发送验证码" }}
          </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
                :loading="loading"
                type="success"
                size="default"
                class="register_btn"
                @click="register"
            >注册
            </el-button>
            <el-button
                type="primary"
                size="default"
                class="back_login_btn"
                @click="backToLogin"
            >返回登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>
<script setup lang="ts">
import { Lock, User, Message } from "@element-plus/icons-vue";
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
//@ts-ignore
import { userRegisterUsingPost } from "@/api/userController";
import request from "@/utils/request";
// 收集账号与密码的数据
let registerForm = reactive({

  userAccount: "",
  userPassword: "",
  checkPassword: "",
  code: "",
  email: "",
  role: ""
});

// 获取registerForms组件
let registerForms = ref();
// 定义变量控制按钮加载效果
let loading = ref(false);
// 获取路由器
const router = useRouter();

// 倒计时相关
let countdown = ref(60);
let isSendingCode = ref(false);

// 校验用户名
const validatorUserName = (_rule: any, value: any, callback: any) => {
  if (/^\w{4,15}$/.test(value)) {
    callback();
  } else {
    callback(new Error("账号长度应该在4位-15位之间"));
  }
};

// 校验密码
const validatorPassword = (_rule: any, value: any, callback: any) => {
  if (/^\w{8,15}$/.test(value)) {
    callback();
  } else {
    callback(new Error("密码长度应该在8位-15位之间"));
  }
};

// 校验确认密码
const validatorCheckPassword = (_rule: any, value: any, callback: any) => {
  if (registerForm.userPassword !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

// 校验邮箱
const validatorEmail = (_rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("邮箱不能为空"));
  } else if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value)) {
    callback(new Error("邮箱格式不正确"));
  } else {
    callback();
  }
};

// 定义表单校验参数
const rules = {
  userAccount: [{ trigger: "change", validator: validatorUserName }],
  userPassword: [{ trigger: "change", validator: validatorPassword }],
  checkPassword: [{ trigger: "change", validator: validatorCheckPassword }],
  email: [{ trigger: "change", validator: validatorEmail }]
};

// 发送验证码
const sendVerificationCode = async () => {
  if (!registerForm.email) {
    ElMessage.error("请先填写邮箱");
    return;
  }

  // 触发邮箱校验
  const emailValid = await new Promise((resolve) => {
    registerForms.value.validateField("email", (valid: boolean) => resolve(valid));
  });

  if (!emailValid) {
    ElMessage.error("邮箱格式不正确");
    return;
  }

  try {
    const formData = new FormData();
    formData.append('email', registerForm.email);
    // 调用接口发送验证码
    const result = await request.post("/api/user/send/code",formData);
    console.log("发送验证码 is ", result);

    //@ts-ignore
    if (result.code === 200) {
      ElMessage.success("验证码已发送，请查收邮箱");
      isSendingCode.value = true;

      // 开始倒计时
      const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer);
          countdown.value = 60;
          isSendingCode.value = false;
        }
      }, 1000);
    } else {
      //@ts-ignore
      ElMessage.error(result.message || "验证码发送失败");
    }
  } catch (error) {
    ElMessage.error("验证码发送失败，请稍后再试");
   }
};

// 注册按钮的回调
const register = async () => {
  // 保证全部表单校验通过再发请求
  const valid = await new Promise((resolve) => {
    registerForms.value.validate((valid: boolean) => resolve(valid));
  });

  if (!valid) {
    ElMessage.error("表单参数不合法");
    return;
  }

  // 开始注册
  loading.value = true;
  try {
    const result = await request.post("/api/user/register",registerForm);
    //@ts-ignore
    if (result.code === 200) {
      ElMessage.success("注册成功");
      await router.push("/login");
    } else {
      //@ts-ignore
      ElMessage.error(result.message || "注册失败");
    }
  } catch (error) {
    ElMessage.error("注册失败，请稍后再试");
  } finally {
    loading.value = false;
  }
};

// 返回登录按钮的回调
const backToLogin = () => {
  router.push("/login");
};
</script>
<style scoped lang="scss">
.register_container {
  width: 100%;
  height: 100vh;
  background: url("../../assets/images/background.jpg") no-repeat;
  background-size: cover;

  .register_form {
    position: relative;
    width: 80%;
    top: 6vh;
    background: url("../../assets/images/login_form.png") no-repeat;
    background-size: cover;
    padding: 40px;

    h1 {
      color: white;
      font-size: 40px;
    }

    h2 {
      font-size: 20px;
      color: white;
      margin: 20px 0px;
    }

    .register_btn {
      width: 20%;
    }

    .back_login_btn {
      width: 20%;
    }
  }
}
</style>
